<template>
  <el-dialog
    v-model="dialogVisible"
    width="600px"
    :close-on-click-modal="false"
    destroy-on-close
    class="login-dialog"
  >
    <el-tabs v-model="activeTab" class="login-tabs">
      <!-- 登录标签页 -->
      <el-tab-pane label="Login" name="login">
        <div class="login-form">
          <form @submit.prevent="handleLogin">
            <div class="form-group">
              <label for="login-username" class="form-label">Username:</label>
              <input
                id="login-username"
                v-model="loginForm.username"
                type="text"
                required
                class="form-input"
                :class="{ error: loginErrors.username }"
                placeholder="Enter your username"
              />
              <div v-if="loginErrors.username" class="error-message">{{ loginErrors.username }}</div>
            </div>
            
            <div class="form-group">
              <label for="login-password" class="form-label">Password:</label>
              <input
                id="login-password"
                v-model="loginForm.password"
                type="password"
                required
                class="form-input"
                :class="{ error: loginErrors.password }"
                placeholder="Enter your password"
              />
              <div v-if="loginErrors.password" class="error-message">{{ loginErrors.password }}</div>
            </div>
            
            <button type="submit" class="submit-button" :disabled="loginLoading">
              <span v-if="loginLoading">Logging in...</span>
              <span v-else>Login</span>
            </button>
          </form>
          
          <div class="switch-link">
            Don't have an account? 
            <a @click="switchTab('register')">Register</a>
          </div>
          
          <!-- 分割线 -->
          <div class="divider">Or continue with</div>
          
          <!-- Google登录按钮 -->
          <button type="button" class="google-button" @click="handleGoogleLogin">
            <svg class="w-5 h-5" viewBox="0 0 24 24" width="20" height="20">
              <path fill="#4285F4" d="M22.56 12.25c0-.78-.07-1.53-.2-2.25H12v4.26h5.92c-.26 1.37-1.04 2.53-2.21 3.31v2.77h3.57c2.08-1.92 3.28-4.74 3.28-8.09z"/>
              <path fill="#34A853" d="M12 23c2.97 0 5.46-.98 7.28-2.66l-3.57-2.77c-.98.66-2.23 1.06-3.71 1.06-2.86 0-5.29-1.93-6.16-4.53H2.18v2.84C3.99 20.53 7.7 23 12 23z"/>
              <path fill="#FBBC05" d="M5.84 14.09c-.22-.66-.35-1.36-.35-2.09s.13-1.43.35-2.09V7.07H2.18C1.43 8.55 1 10.22 1 12s.43 3.45 1.18 4.93l2.85-2.22.81-.62z"/>
              <path fill="#EA4335" d="M12 5.38c1.62 0 3.06.56 4.21 1.64l3.15-3.15C17.45 2.09 14.97 1 12 1 7.7 1 3.99 3.47 2.18 7.07l3.66 2.84c.87-2.6 3.3-4.53 6.16-4.53z"/>
            </svg>
            Continue with Google
          </button>
        </div>
      </el-tab-pane>
      
      <!-- 注册标签页 -->
      <el-tab-pane label="Register" name="register">
        <div class="register-form">
          <form @submit.prevent="handleRegister">
            <div class="form-group">
              <label for="register-fullname" class="form-label">Full name:</label>
              <input
                id="register-fullname"
                v-model="registerForm.fullname"
                type="text"
                required
                class="form-input"
                :class="{ error: registerErrors.fullname }"
                placeholder="Enter your full name"
              />
              <div v-if="registerErrors.fullname" class="error-message">{{ registerErrors.fullname }}</div>
            </div>
            
            <div class="form-group">
              <label for="register-username" class="form-label">Username:</label>
              <input
                id="register-username"
                v-model="registerForm.username"
                type="text"
                required
                class="form-input"
                :class="{ error: registerErrors.username }"
                placeholder="Enter your username"
              />
              <div v-if="registerErrors.username" class="error-message">{{ registerErrors.username }}</div>
            </div>
            
            <div class="form-group">
              <label for="register-email" class="form-label">Email:</label>
              <input
                id="register-email"
                v-model="registerForm.email"
                type="email"
                required
                class="form-input"
                :class="{ error: registerErrors.email }"
                placeholder="Enter your email"
              />
              <div v-if="registerErrors.email" class="error-message">{{ registerErrors.email }}</div>
            </div>
            
            <div class="form-group">
              <label for="register-password" class="form-label">Password:</label>
              <input
                id="register-password"
                v-model="registerForm.password"
                type="password"
                required
                class="form-input"
                :class="{ error: registerErrors.password }"
                placeholder="Enter your password"
              />
              <div v-if="registerErrors.password" class="error-message">{{ registerErrors.password }}</div>
            </div>
            
            <div class="form-group">
              <label for="register-confirmPassword" class="form-label">Confirm Password:</label>
              <input
                id="register-confirmPassword"
                v-model="registerForm.confirmPassword"
                type="password"
                required
                class="form-input"
                :class="{ error: registerErrors.confirmPassword }"
                placeholder="Confirm your password"
              />
              <div v-if="registerErrors.confirmPassword" class="error-message">{{ registerErrors.confirmPassword }}</div>
            </div>
            
            <button type="submit" class="submit-button" :disabled="registerLoading">
              <span v-if="registerLoading">Registering...</span>
              <span v-else>Register</span>
            </button>
          </form>
          
          <div class="switch-link">
            Yes I have an account? 
            <a @click="switchTab('login')">Login</a>
          </div>
        </div>
      </el-tab-pane>
    </el-tabs>
  </el-dialog>
</template>

<script setup>
import { ref, onMounted, onUnmounted } from 'vue'
import { useLoginDialog } from '~/composables/useLoginDialog'
import { userApi } from '~/public/utils/api'

const { dialogVisible, activeTab, redirectPath, hideLoginDialog, switchTab, clearRedirectPath } = useLoginDialog()
const { $auth, $toast } = useNuxtApp()

// 登录表单数据
const loginForm = ref({
  username: '',
  password: ''
})

const loginErrors = ref({})
const loginLoading = ref(false)

// 注册表单数据
const registerForm = ref({
  fullname: '',
  username: '',
  email: '',
  password: '',
  confirmPassword: ''
})

const registerErrors = ref({})
const registerLoading = ref(false)

/**
 * 处理登录
 */
const handleLogin = async () => {
  loginErrors.value = {}
  
  if (!loginForm.value.username || !loginForm.value.password) {
    $toast.error('Please fill in all fields')
    return
  }
  
  loginLoading.value = true
  
  try {
    // Step 1: 调用登录 API
    const result = await userApi.login({
      userName: loginForm.value.username,
      password: loginForm.value.password
    })
    
    console.log('Login successful:', result)
    
    // Step 2: 存储 token 并获取完整用户信息
    if (result.data && result.data.token) {
      // 先存储 token（getUserInfo API 需要）
      localStorage.setItem('token', result.data.token)
      
      // Step 3: 获取完整用户信息
      try {
        const userInfoResult = await userApi.getUserInfo()
        
        if (userInfoResult.data) {
          // Step 4: 使用完整用户信息登录
          $auth.login({
            id: result.data.memberId,
            fullName: userInfoResult.data.fullName || loginForm.value.username,
            name: loginForm.value.username,
            email: userInfoResult.data.email || loginForm.value.username,
            position: userInfoResult.data.position,
            phone: userInfoResult.data.phone,
            companyName: userInfoResult.data.companyName,
            companyAddress: userInfoResult.data.companyAddress
          }, result.data.token)
        }
      } catch (userInfoError) {
        console.error('Failed to get user info:', userInfoError)
        // 降级：如果 getUserInfo 失败，使用基本信息
        $auth.login({
          id: result.data.memberId,
          fullName: loginForm.value.username,
          name: loginForm.value.username,
          email: loginForm.value.username
        }, result.data.token)
      }
    }
    
    $toast.success('Login successful!')
    
    // 关闭弹窗
    hideLoginDialog()
    
    // 根据 redirectPath 决定是否跳转
    if (redirectPath.value) {
      await navigateTo(redirectPath.value)
      clearRedirectPath()
    }
    
    // 重置表单
    loginForm.value = { username: '', password: '' }
  } catch (error) {
    console.error('Login failed:', error)
    $toast.error(`Login failed: ${error.message || 'Unknown error'}`)
  } finally {
    loginLoading.value = false
  }
}

/**
 * 处理注册
 */
const handleRegister = async () => {
  registerErrors.value = {}
  
  // 验证密码一致性
  if (registerForm.value.password !== registerForm.value.confirmPassword) {
    registerErrors.value.confirmPassword = 'Passwords do not match'
    $toast.error('Passwords do not match')
    return
  }
  
  registerLoading.value = true
  
  try {
    // 获取 recordId（如果有）
    let recordId = localStorage.getItem('recordId')
    
    // 调用注册 API
    const result = await userApi.register({
      userName: registerForm.value.username,
      password: registerForm.value.password,
      email: registerForm.value.email,
      fullName: registerForm.value.fullname,
      recordId: recordId
    })
    
    console.log('Registration successful:', result)
    $toast.success('Registration successful! Please login.')
    
    // 切换到登录标签页
    switchTab('login')
    
    // 重置表单
    registerForm.value = {
      fullname: '',
      username: '',
      email: '',
      password: '',
      confirmPassword: ''
    }
  } catch (error) {
    console.error('Registration failed:', error)
    $toast.error(`Registration failed: ${error.message || 'Unknown error'}`)
  } finally {
    registerLoading.value = false
  }
}

/**
 * 处理 Google 登录（弹窗方式）
 */
const handleGoogleLogin = () => {
  const width = 500
  const height = 600
  const left = (screen.width - width) / 2
  const top = (screen.height - height) / 2
  
  // 在弹出窗口中打开 Google OAuth
  const popup = window.open(
    'https://cbam.hongyuan3e.com/prod-api/api/auth/render?redirect_uri=https://cbam.hongyuan3e.com/auth/google/callback',
    'googleLogin',
    `width=${width},height=${height},left=${left},top=${top}`
  )
  
  // 检测弹窗是否被拦截
  if (!popup || popup.closed) {
    $toast.error('Please allow popups for this website')
    return
  }
  
  // 监听来自回调页面的消息
  window.addEventListener('message', handleOAuthMessage)
}

/**
 * 处理 OAuth 回调消息
 */
const handleOAuthMessage = (event) => {
  // 验证来源
  if (event.origin !== window.location.origin) return
  
  if (event.data.type === 'GOOGLE_LOGIN_SUCCESS') {
    const { user, token } = event.data
    
    // 使用 auth 插件登录
    $auth.login(user, token)
    
    $toast.success('Google login successful!')
    
    // 关闭弹窗
    hideLoginDialog()
    
    // 处理跳转
    if (redirectPath.value) {
      navigateTo(redirectPath.value)
      clearRedirectPath()
    }
    
    // 移除事件监听
    window.removeEventListener('message', handleOAuthMessage)
  } else if (event.data.type === 'GOOGLE_LOGIN_ERROR') {
    $toast.error('Google login failed, please try again')
    window.removeEventListener('message', handleOAuthMessage)
  }
}

// 组件卸载时移除事件监听
onUnmounted(() => {
  window.removeEventListener('message', handleOAuthMessage)
})
</script>

<style scoped>
/* 弹窗整体样式 */
:deep(.login-dialog) {
  border-radius: 12px;
  overflow: hidden;
}

:deep(.login-dialog .el-dialog__header) {
  padding: 0;
  margin: 0;
}

:deep(.login-dialog .el-dialog__body) {
  padding: 30px 40px;
}

/* 标签页样式 */
:deep(.login-tabs .el-tabs__nav-wrap::after) {
  background-color: #e5e7eb;
}

:deep(.login-tabs .el-tabs__active-bar) {
  background-color: #0066a1;
  height: 3px;
}

:deep(.login-tabs .el-tabs__item) {
  font-size: 18px;
  font-weight: 500;
  color: #6b7280;
  padding: 20px 30px;
}

:deep(.login-tabs .el-tabs__item.is-active) {
  color: #0066a1;
}

:deep(.login-tabs .el-tabs__item:hover) {
  color: #0066a1;
}

/* 表单样式 */
.login-form,
.register-form {
  margin-top: 20px;
}

.form-group {
  margin-bottom: 20px;
}

.form-label {
  display: block;
  font-size: 14px;
  font-weight: 500;
  color: #374151;
  margin-bottom: 8px;
}

.form-input {
  width: 100%;
  padding: 12px 16px;
  border: 1px solid #d1d5db;
  border-radius: 24px;
  font-size: 14px;
  transition: all 0.3s;
  box-sizing: border-box;
}

.form-input:focus {
  outline: none;
  border-color: #0066a1;
  box-shadow: 0 0 0 3px rgba(0, 102, 161, 0.1);
}

.form-input.error {
  border-color: #ef4444;
}

.error-message {
  color: #ef4444;
  font-size: 12px;
  margin-top: 4px;
}

/* 按钮样式 */
.submit-button {
  width: 100%;
  background-color: #0066a1;
  color: white;
  padding: 12px;
  border-radius: 24px;
  font-weight: 500;
  font-size: 15px;
  border: none;
  cursor: pointer;
  transition: all 0.3s;
  margin-top: 10px;
}

.submit-button:hover:not(:disabled) {
  background-color: #005589;
  transform: translateY(-1px);
  box-shadow: 0 4px 12px rgba(0, 102, 161, 0.3);
}

.submit-button:active:not(:disabled) {
  transform: translateY(0);
}

.submit-button:disabled {
  opacity: 0.6;
  cursor: not-allowed;
}

/* Google 登录按钮 */
.google-button {
  width: 100%;
  display: flex;
  align-items: center;
  justify-content: center;
  padding: 12px;
  border: 1px solid #d1d5db;
  border-radius: 24px;
  background: white;
  color: #374151;
  font-weight: 500;
  font-size: 15px;
  cursor: pointer;
  transition: all 0.3s;
}

.google-button:hover {
  background-color: #f9fafb;
  border-color: #9ca3af;
}

.google-button svg {
  margin-right: 8px;
}

/* 分割线 */
.divider {
  display: flex;
  align-items: center;
  text-align: center;
  margin: 24px 0;
  color: #6b7280;
  font-size: 14px;
}

.divider::before,
.divider::after {
  content: '';
  flex: 1;
  border-bottom: 1px solid #e5e7eb;
}

.divider::before {
  margin-right: 16px;
}

.divider::after {
  margin-left: 16px;
}

/* 切换链接 */
.switch-link {
  text-align: center;
  margin-top: 16px;
  color: #6b7280;
  font-size: 14px;
}

.switch-link a {
  color: #0066a1;
  font-weight: 500;
  text-decoration: none;
  cursor: pointer;
}

.switch-link a:hover {
  text-decoration: underline;
}
</style>

